package pl.edu.pk.adcampaignfacebook.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import pl.edu.pk.adcampaignfacebook.domain.AccountRole;

import pl.edu.pk.adcampaignfacebook.domain.Administrator;
import pl.edu.pk.adcampaignfacebook.service.AccountService;
import pl.edu.pk.adcampaignfacebook.exception.UserExistsException;

@Controller
public class AdministratorController
{
	 @Autowired
	 AccountService accountService;

	 @Autowired  
	 private MessageSource messageSource;
	 
	 @RequestMapping(value = "/administrator/add", method = RequestMethod.GET)
	 public ModelAndView add()
	 {
		 ModelAndView mav = new ModelAndView("/administrator/add");
		 mav.addObject("administrator", new Administrator());
		 return mav;
	 }
	 
	 @RequestMapping(value = "/administrator/add", method = RequestMethod.POST)
	 public ModelAndView add(@Valid Administrator admin, BindingResult result)
	 {
		 ModelAndView mav = new ModelAndView("administrator/add");
		 
		 if (!admin.getPassword().equals(admin.getRepeatedPassword())) 
		 {
			 result.addError(new FieldError("administrator", "repeatedPassword", messageSource.getMessage("addUser.equalPassword", null, Locale.getDefault())));
		 }
		 
		 if (result.hasErrors()) 
		 {
			 mav.addObject("administrator", admin);
			 return mav;
		 }
		 
//		 List<AccountRole> ar = new ArrayList<AccountRole>();
//		 ar.add(new AccountRole("ROLE_ADMIN"));
		 
		 try
		 {
			 accountService.registerAccount(admin);//, ar);
		 } 
		 catch (UserExistsException e)
		 {
			 result.reject("user.exists");
			 result.addError(new FieldError("administrator", "username", messageSource.getMessage("addUser.userExists", null, Locale.getDefault())));
			 mav.addObject("administrator", admin);
			 return mav;
		 }
		 
         mav.setViewName("redirect:/index.html");
		 return mav;
	 }
	 
	 // Lista ról dla kontrolki select w administrator/add.jsp
	 @ModelAttribute("roles")
	 public ArrayList<String> getList()
	 {
	     ArrayList<String> itemList = new ArrayList<String>();
	     itemList.add("ROLE_ADMIN");
	     itemList.add("ROLE_USER");
	     return itemList;
	 }
}